const port = 5000
import cors from '@koa/cors'
import Koa from 'koa'
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import { DataTypes, Op, Sequelize } from 'sequelize'

const app = new Koa()
const router = new Router()

const sequelize = new Sequelize('StuDB', 'root', '123456', {
    dialect: 'mysql',
    host: 'localhost',
})
const Students = sequelize.define('StuDB', {
    Name: {
        type: DataTypes.STRING,
        allowNull: false
    },
    Sex: {
        type: DataTypes.CHAR,
        allowNull: false
    },
    Age: {
        type: DataTypes.INTEGER,
        allowNull: true
    },
    sClass: {
        type: DataTypes.STRING,
        allowNull: false
    }
})
// await sequelize.sync()
app.use(cors())
app.use(bodyParser())

router.get('/student', async (ctx, next) => {
    let keyword = ctx.request.query.keyword || ''
    let where;
    if (keyword.trim()) {
        where = {
            [Op.or]: {
                Name: {
                    [Op.like]: `%${keyword}%`
                },
                Sex: {
                    [Op.like]: `%${keyword}%`
                },
                sClass: {
                    [Op.like]: `%${keyword}%`
                },
                Age: {
                    [Op.like]: `%${keyword}%`
                }
            }
        }
    }

    const obj = await Students.findAll({ where })
    ctx.body = {
        code: 666,
        data: obj,
        msg: 'success'
    }
})

router.get('/student/:id',async(ctx,next)=>{
    let id =ctx.params.id || 0
    const obj =await Students.findByPk(id)
    ctx.body = {
        code: 666,
        data: obj,
        msg: 'success'
    }
})

router.post('/student',async(ctx,next)=>{
    let data =ctx.request.body
    const obj =await Students.create(data)
    ctx.body = {
        code: 666,
        data: obj,
        msg: 'success'
    }
})

router.delete('/student/:id',async(ctx,next)=>{
    let id =ctx.params.id || 0
    const obj =await Students.destroy({where:{id}})
    ctx.body = {
        code: 666,
        data: obj,
        msg: 'success'
    }
})

router.put('/student/:id',async(ctx,next)=>{
    let id =ctx.params.id || 0
    const data =ctx.request.body
    const obj =await Students.update(data,{where:{id}})
    ctx.body = {
        code: 666,
        data: obj,
        msg: 'success'
    }
})
app.use(router.routes())

app.listen(port, () => {
    console.log(`服务运行在：http://localhost:${port}`);
})